package com.idanchuang.component.shadow.route.common.aop;

import com.idanchuang.component.core.helper.EnvContext;
import com.idanchuang.component.shadow.route.common.conf.ShadowRouteProperties;
import com.idanchuang.component.shadow.route.common.context.ShadowRouteContext;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Shadow Route Data Source Aspect
 *
 * @author Raistlin
 */
@Aspect
public class ShadowRouteDataSourceAspect {

    private final Logger logger = LoggerFactory.getLogger(ShadowRouteDataSourceAspect.class.getName());

    private final ShadowRouteProperties properties;

    public ShadowRouteDataSourceAspect(ShadowRouteProperties properties) {
        this.properties = properties;
    }

    // execution(* com.idanchuang..*.controller..*.*(..)) || execution(* com.idanchuang..*.service..*.*(..))
    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.PostMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void pointcut() {
    }

    @Before(value = "pointcut()")
    public void before() {
        if (EnvContext.isPressure()) {
            ShadowRouteContext.setRoutingKey(properties.getShadowDataSourceName());
        } else {
            ShadowRouteContext.setRoutingKey(properties.getActualDataSourceName());
        }
    }

    @After(value = "pointcut()")
    public void after() {
        ShadowRouteContext.reset();
    }

}
